package king.dominic.jlibrary.util;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;

import java.io.File;

import king.dominic.jlibrary.R;
import king.dominic.jlibrary.view.WindowUtil;


/**
 * @author DominicKing
 */
public class NewApk {
    private NewApk() {
    }

    public static void install(Context context, File file) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void updateNotification(Context context, int progress, int max) {
        notify(notificationManager(context), notificationBuilder(context).setProgress(max, progress, false));
    }

    public static void failNotification(Context context) {
        notify(notificationManager(context), failNotificationBuilder(context));
    }

    public static void successNotification(Context context) {
        notify(notificationManager(context), successNotificationBuilder(context));
    }

    private static NotificationCompat.Builder failNotificationBuilder(Context context) {
        return new NotificationCompat.Builder(context)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(context.getString(R.string.update_fail))
                .setAutoCancel(true)
                .setSmallIcon(WindowUtil.getAppMipmapId(context, "ic_launcher"));
    }

    private static NotificationCompat.Builder successNotificationBuilder(Context context) {
        return new NotificationCompat.Builder(context)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(context.getString(R.string.update_success))
                .setAutoCancel(true)
                .setSmallIcon(WindowUtil.getAppMipmapId(context, "ic_launcher"));
    }

    private static NotificationCompat.Builder notificationBuilder(Context context) {
        return new NotificationCompat.Builder(context)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(context.getString(R.string.update_now))
                .setSmallIcon(WindowUtil.getAppMipmapId(context, "ic_launcher"));
    }

    private static void notify(NotificationManager notificationManager, NotificationCompat.Builder builder) {
        notificationManager.notify(android.os.Process.myUid(), builder.build());
    }

    private static NotificationManager notificationManager(Context context) {
        return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }
}
